package com.alibaba.jingn.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    public static Timestamp getNowTimestamp(){
        Date now = new Date();
        Timestamp timestamp = new Timestamp(now.getTime());
        return timestamp;
    }

    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        return formatDuring(diff);
    }

    /**
     *
     * @param mss 要转换的毫秒数
     * @return 该毫秒数转换为 * days * hours * minutes * seconds 后的格式
     * @author fy.zhang
     */
    public static String formatDuring(long mss) {
        StringBuffer result = new StringBuffer();
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // 计算差多少天
        long day = mss / nd;
        // 计算差多少小时
        long hour = mss % nd / nh;
        // 计算差多少分钟
        long min = mss % nd % nh / nm;
        if(day != 0)
        result.append(day + "天");
        if(hour != 0)
        result.append(hour + "小时");
        result.append(min + "分钟");
        return result.toString();
    }

    /**
     * 获取上一个月的第一天
     * @param date
     * @return
     */
    public static Date getLastMonthFirstDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)- 1 ); // 设置为上一个月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date lastMonth = calendar.getTime();
        return lastMonth;
    }

    /**
     * 获取上一个月的最后一天
     * @param date
     * @return
     */
    public static Date getLastMonthLastDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1 ); // 设置为上一个月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date lastMonth = calendar.getTime();
        return lastMonth;
    }

    /**
     * 获取下一个月的最后一天
     * @param date
     * @return
     */
    public static Date getNextMonthLastDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) +1); // 设置为上一个月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date lastMonth = calendar.getTime();
        return lastMonth;
    }

    /**
     * 获取下一个月的第一天
     * @param date
     * @return
     */
    public static Date getNextMonthFirstDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) +1 ); // 设置为上一个月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date lastMonth = calendar.getTime();
        return lastMonth;
    }

    /**
     * 获取当前月的第一天
     * @param date
     * @return
     */
    public static Date getCurrentMonthFirstDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)  ); // 设置为当前月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date lastMonth = calendar.getTime();
        return lastMonth;
    }

    /**
     * 获取当前月的最后一天
     * @param date
     * @return
     */
    public static Date getCurrentMonthLastDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)  ); // 设置为当前月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date lastMonth = calendar.getTime();
        return lastMonth;
    }

    /**
     * 获取指定日期的 指定偏移量后的日期
     * @param date
     * @return
     */
    public static Date getDayOfOffset(Date date,int offset){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)  ); // 设置为当前月
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + offset); // 设置为上一个月
        Date days = calendar.getTime();
        return days;
    }

    /**
     * 获取指定月的天数
     * @param year
     * @param month
     * @return
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static Integer getWeekOfDate(Date dt) {
        Integer[] weekDays = {7, 1, 2, 3, 4, 5, 6};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 获取当前日期 号数
     *
     * @param dt
     */
    public static Integer getDayOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int month = cal.get(Calendar.DATE);
        return  month;
    }


    /**
     * 获取当前日期月份
     *
     * @param dt
     */
    public static Integer getMonthOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int month = cal.get(Calendar.MONTH)+1;
        return  month;
    }

    /**
     * 获取当前日期年份
     *
     * @param dt
     */
    public static Integer getYearOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int year = cal.get(Calendar.YEAR);
        return  year;
    }

    /**
     * 获取两个日期之间的时间列表
     * @param startDate
     * @param endxDate
     * @return
     */
    public static List<String> getTimesBetween(String startDate, String endxDate){
        SimpleDateFormat sdf ;
        int calendarType;

        switch (startDate.length()){
            case 10:
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                calendarType = Calendar.DATE;
                break;
            case 7:
                sdf = new SimpleDateFormat("yyyy-MM");
                calendarType = Calendar.MONTH;
                break;
            case 4:
                sdf = new SimpleDateFormat("yyyy");
                calendarType = Calendar.YEAR;
                break;
            default:
                return null;
        }

        List<String> result = new ArrayList<>();
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        try {
            min.setTime(sdf.parse(startDate.replaceAll("/","-")));
            min.add(calendarType, 0);
            max.setTime(sdf.parse(endxDate.replaceAll("/","-")));
            max.add(calendarType, 1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(min.getTime()));
            curr.add(calendarType, 1);
        }
        return result;
    }

    public static Integer getWeekNum(String t){
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);//设置周一为一周的第一天
        cal.setTime(DateUtils.parseDate(t));
        int num = cal.get(Calendar.WEEK_OF_YEAR);
        return num;
    }

    /**
     * 当年第一天
     *
     * @param date
     *            日期
     * @return 天
     * @throws Exception
     *             异常
     */
    public static String getThisYear(String date) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format3 = new SimpleDateFormat("yyyy");
        Date time = format3.parse(date);
        String time1 = format3.format(time);
        Date startTime = format.parse(time1 + "-01-01");
        String dates = format.format(startTime);
        return dates;
    }

    public static int getNextYear(){
        Calendar calendar = Calendar.getInstance();
        int i = calendar.get(Calendar.YEAR);
        return i + 1;
    }

    public static void main(String[] args) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2019,01,2);
        System.out.println("上个月的第一天==="+DateFormatUtils.format(getLastMonthFirstDay(new Date()),"yyyy-MM-dd"));
        System.out.println("上个月的最后一天==="+DateFormatUtils.format(getLastMonthLastDay(new Date()),"yyyy-MM-dd"));
        System.out.println("下个月的最后一天==="+DateFormatUtils.format(getNextMonthLastDay(new Date()),"yyyy-MM-dd"));
        System.out.println("当前月的第一天==="+DateFormatUtils.format(getCurrentMonthFirstDay(new Date()),"yyyy-MM-dd"));
        System.out.println("下个月的第一天==="+DateFormatUtils.format(getNextMonthFirstDay(new Date()),"yyyy-MM-dd"));
        System.out.println("当前月的最后一天==="+DateFormatUtils.format(getCurrentMonthLastDay(new Date()),"yyyy-MM-dd"));
        System.out.println("当前天偏移指定天数后==="+DateFormatUtils.format(getDayOfOffset(new Date(),4),"yyyy-MM-dd"));
        System.out.println(formatDuring(7200000));
        System.out.println(getTimesBetween("2018-10","2019-11"));
        System.out.println("2019-03-22".substring(0,7));
        System.out.println(getWeekNum("2019-01-07"));
        System.out.println(getThisYear(DateFormatUtils.format(new Date(),"yyyy-MM-dd")));
        System.out.println(getTimesBetween("2019/11/20","2019/12/30"));

        System.out.println(DateFormatUtils.format(getDayOfOffset(new Date(),10),"yyyy-MM-dd HH:mm:ss"));
        System.out.println(getNextYear());
    }

}
